package com.ruoyi.ucar.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ucar.common.CommonVoResp;
import com.ruoyi.ucar.util.CommonUtil;
import com.ruoyi.ucar.util.SmsUtil;
import com.ruoyi.ucar.voreq.SendMessageCodeVoReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/ucar/sms")
@Api(value = "短信管理",tags = "短信管理模块接口")
public class SmsController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SmsUtil smsUtil;

    @ApiOperation("6位随机数字短信验证码-mobile使用-匿名")
    @PostMapping("/sendMessageCode")
    @Anonymous
    public CommonVoResp<String> sendSms(@RequestBody SendMessageCodeVoReq sendMessageCodeVoReq)   {
        String  mobilePhoneNumber=sendMessageCodeVoReq.getMobilePhoneNumber();
        String code = RandomStringUtils.randomNumeric(6);
        CommonVoResp<String> commonVoResp=new CommonVoResp<>();
        if(!CommonUtil.isMobilePhoneValid(mobilePhoneNumber)){
            commonVoResp.setCode(500);
            commonVoResp.setMessage("手机号码格式错误！");
        }
        if(StringUtils.isNotEmpty(redisTemplate.opsForValue().get("sms:" + mobilePhoneNumber))){
            commonVoResp.setCode(500);
            commonVoResp.setMessage("短信验证码5分钟以内不允许重复发送");
        }else{
            // 调用短信平台API（示例使用阿里云）
            try {
                SendSmsResponse response = smsUtil.sendVerificationCode(
                        mobilePhoneNumber,
                        code,
                        "SMS_464530719"
                );
               if("isv.MOBILE_NUMBER_ILLEGAL".equals(response.getBody().getCode())){
                   commonVoResp.setCode(500);
                   commonVoResp.setMessage("手机号码格式错误");
               }
            } catch (Exception e) {
                commonVoResp.setCode(500);
                commonVoResp.setMessage("短信验证码发送失败");
            }
            // 存储验证码到Redis（5分钟过期）
            redisTemplate.opsForValue().set(
                    "sms:" + mobilePhoneNumber,
                    code,
                    5, TimeUnit.MINUTES
            );
        }
        return commonVoResp;
    }
}